<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

/**
 * WordPress文章集合资源类
 *
 * 负责处理文章列表的分页和格式化
 */
class PostCollection extends ResourceCollection
{
    /**
     * 分页信息
     */
    protected array $pagination;

    /**
     * 构造函数
     *
     * @param mixed $resource
     * @param array $pagination
     */
    public function __construct($resource, array $pagination = [])
    {
        parent::__construct($resource);
        $this->pagination = $pagination;
    }

    /**
     * 将资源集合转换为数组
     *
     * @param Request $request
     * @return array
     */
    public function toArray(Request $request): array
    {
        return [
            'list' => PostResource::collection($this->collection),
            'pagination' => $this->pagination,
        ];
    }

    /**
     * 构建分页信息
     *
     * @param \WP_Query $wp_query
     * @param Request $request
     * @return array
     */
    public static function buildPagination(\WP_Query $wp_query, Request $request): array
    {
        $page = (int) $request->get('page', 1);
        $limit = (int) $request->get('limit', 10);
        $total_posts = $wp_query->found_posts;
        $total_pages = $wp_query->max_num_pages;

        return [
            'current_page' => $page,
            'limit' => $limit,
            'total' => $total_posts,
            'total_pages' => $total_pages,
            'has_next_page' => $page < $total_pages,
            'has_prev_page' => $page > 1,
        ];
    }
}
